<?php


namespace app\api\services;


use qrcode\QrcodeFile;
use think\facade\Cache;
use think\facade\Request;

/**
 * Class QrcodeService
 * @package app\api\services
 * @desc 二维码相关服务
 */
class QrcodeService
{
    use ApiTrait;

    public $appid = 'wx5799bb07ce1718e6';//小程序appid
    public $secret = '5ff1ca8cd900d2290166dda83fe459ac';//小程序秘钥

    /**
     * @desc 生成二维码
     * @param array $data 生成二维码数据
     */
    public function makeQrcode($data)
    {
        $qrcode = new QrcodeFile();
        if (is_array($data)) {
            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        }
        $fileName = 'qrcode/' . date('YmdHis') . '.png';
        $filePath = ROOT_PATH . 'public/' . $fileName;
        $ret      = $qrcode->png($data, $filePath, 'L', 6, 2, true);
        $fileUrl  = Request::domain() . '/' . $fileName;
//        $img=ob_get_contents(); ob_end_clean();
//        $imgStr = '<img src="data:image/png;base64,'.base64_encode($img).'" />';
        return $fileUrl;
    }

    //    获取accesstoken

    /**
     * @desc 获取access_token
     * @return mixed|string
     */
    public function getAccesstoken()
    {
        $access_token = '';
        $cacheKey     = 'access_token5';
        $cacheData    = Cache::get($cacheKey);
        if ($cacheData) {
            $access_token = $cacheData;
        } else {
            $tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret;
            $res      = $this->curlGet($tokenUrl);
            $resArr   = json_decode($res, true);
            if (isset($resArr['access_token']) && $resArr['access_token']) {
                $access_token = $resArr['access_token'];
                Cache::set($cacheKey, $access_token, $resArr['expires_in']);
            }
        }
        return $access_token;
    }

    // 生成小程序不限量的二维码

    /**
     * @desc 生成带参数不限量的小程序码
     * @param string $page 小程序页面路径 pages/index/index
     * @param string $dataStr 参数 store_id=2
     * @param string $fileName 保存的图片名称 20230810110421.png
     * @return string
     */
    public function makeXcxUnlimitQrcode($page, $dataStr ,$fileName = '')
    {
        $imgPath = '';
        parse_str($dataStr, $dataArr);
        //参数
        $postdata['scene'] = $dataStr;
        // 宽度
        $postdata['width'] = 430;
        // 页面
        $postdata['page'] = $page;
        // 线条颜色
        $postdata['auto_color'] = false;
        //auto_color 为 false 时生效
        $postdata['line_color'] = ['r' => '0', 'g' => '0', 'b' => '0'];
        // 是否有底色为true时是透明的
        $postdata['is_hyaline'] = true;
        $access_token           = $this->getAccesstoken();
        $url                    = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
        $result                 = $this->httpCurl($url, $postdata, 'POST');
        if ($result) {
//            $fileName = date('YmdHis') . '_store' . $dataArr['store_id'] . '.png';
            $path     = './qrcode/';
            $imgPath        = $this->saveBase64ToImg($result, $fileName, $path);
        }
        return \request()->domain().$imgPath;
    }

    // 生成小程序限量100000的二维码
    // $page 页面加参数 pages/index/index?foo=bar
    public function makeXcxlimitQrcode($page)
    {
//        $path="pages/postcard/postcard";
        // 宽度
        $postdata['width'] = 430;
        // 页面
        $postdata['path'] = $page;
        $post_data        = json_encode($postdata);
        $access_token     = $this->getAccesstoken();
        $url              = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" . $access_token;
        $result           = $this->httpCurl($url, $post_data, 'POST');
        $data             = 'image/png;base64,' . base64_encode($result);
        echo '<img src="data:' . $data . '">';
    }

    /**
     * @desc 保存base64图片到服务器上
     * @param string $result base64图片流
     * @param string $filename 文件名称
     * @param string $path 保存路径
     * @return string
     */
    public function saveBase64ToImg($result, $filename, $path)
    {
        $path = $path . $filename;
        file_put_contents($path, $result, true);
        //输出生成二维码路径
        return trim($path,'.');
    }
}